//
//  OAuthViewController.swift
//  lixiangweibo
//
//  Created by dyy on 15/11/28.
//  Copyright © 2015年 lixianggongzuoshi. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class OAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        userOAuthPage()
        //view = webView
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "defluatAccount")
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        SVProgressHUD.dismiss()
    }
    
    func defluatAccount(){
        
        let jsString = "document.getElementById('userId').value = '15995729215@163.com',document.getElementById('passwd').value = 'lijingguo1987'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    
    override func loadView() {
        view=webView
        webView.delegate = self
        
        
    }
    //关闭窗口
    @objc  private func close(){
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    private func userOAuthPage(){
        
        let  urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        
        if let url = NSURL(string:urlString) {
            
            let request = NSURLRequest(URL: url)
            webView.loadRequest(request)
            
        }
    }
    
}

 private func loadAccessToken(code: String){
    
    AccountViewModel().loadAccessToken(code) { (error) -> () in
        if error != nil{
        
            SVProgressHUD.showErrorWithStatus("网络不稳,无法访问")
        
        }
        SVProgressHUD.showSuccessWithStatus("你可以玩了")
    
    NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootNotification, object: "welcome")
    }
    
}

extension OAuthViewController: UIWebViewDelegate{
    
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    /*
    https://api.weibo.com/oauth2/authorize?client_id=3562413756&redirect_uri=http://www.itcast.cn
    http://weibo.cn/dpool/ttt/h5/reg.php?wm=4406&appsrc=5Ka7Vy&backURL=https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D3562413756%26response_type%3Dcode%26display%3Dmobile%26redirect_uri%3Dhttp%253A%252F%252Fwww.itcast.cn%26from%3D%26with_cookie%3D)
    Optional(http://m.weibo.cn/reg/index?jp=1&wm=4406&appsrc=5Ka7Vy&backURL=https%3A%2F%2Fapi.weibo.com%2F2%2Foauth2%2Fauthorize%3Fclient_id%3D3562413756%26response_type%3Dcode%26display%3Dmobile%26redirect_uri%3Dhttp%253A%252F%252Fwww.itcast.cn%26from%3D%26with_cookie%3D)
    https://api.weibo.com/oauth2/authorize
    */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //print(request.URL)
        let urlString = request.URL?.absoluteString ?? ""
            
        
        if urlString.hasPrefix("https://api.weibo.com") {
            //是新浪微博的收取页面
            return true
        }
        
        if !urlString.hasPrefix(redirect_uri) {
            return false
        }
        
        
        guard let query = request.URL?.query else {
            
            return false
        }
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        
        loadAccessToken(code)
        
        return false
    }
    
}

